package com.zzb.weikeautosign.threadpool;

import com.alibaba.fastjson.JSONObject;
import com.zzb.weikeautosign.PropertiesUtil;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.log4j.Logger;

import java.util.*;

/**
 * 执行线程池 执行队列
 * Created by zzb on 16/1/19.
 */
public class ThreadQueue extends ArrayDeque<ExcuteThread> {
    private static final Logger log = Logger.getLogger(ThreadQueue.class);
    private static ThreadQueue instances;
    private List<String> runningTaskKey; //运行中任务列表
    private Map<String, JSONObject> completeTaskKey; //运行完成列表
    private static boolean isRun = false;
    private static int maxThreadCount;

    public static ThreadQueue getInstances() {
        if (instances == null) {
            instances = new ThreadQueue();
            maxThreadCount = NumberUtils.toInt(PropertiesUtil.getProperties("config.properties", "maxThreadCount"), 5);
            instances.init();
        }
        return instances;
    }

    //执行一次自动签到+点赞
    public void execute() {
        if (!isRun) {
            isRun = true;
            new Thread(() -> {
                //初始化列表状态
                while (true) {
                    while (CollectionUtils.isNotEmpty(this) && CollectionUtils.size(runningTaskKey) < maxThreadCount) {
                        _appendTask();
                    }
                    //一直一直一直执行,15秒遍历执行列表一次
                    try {
                        Thread.currentThread().sleep(15000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                        log.error(e.getMessage());
                    }
                }
            }).start();
        }
    }

    //移除旧的运行中任务,并把结果放入completeTaskKey map中
    public void removeOldTask(String username, JSONObject result) {
        if (StringUtils.isNotBlank(username)) {
            runningTaskKey.remove(username);
            completeTaskKey.put(username, result);
        }

    }

    /**
     * 为线程加入一个任务
     */
    private void _appendTask() {
        if (CollectionUtils.isNotEmpty(this)) {
            //任务出栈
            ExcuteThread task = this.poll();
            //将任务标识为运行中
            runningTaskKey.add(task.getUserName());
            //执行任务
            task.start();
        }
    }

    /**
     * 初始化运行池
     */
    public void init() {
        runningTaskKey = new ArrayList<>();
        completeTaskKey = new HashMap<>();
        this.clear();
    }
}
